package com.another.bidservice.utils.aliyunutil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectResult;
import com.another.common.utils.common.EmptyUtil;
import com.another.common.utils.common.MyException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * @author Another
 * @version : 1.0
 * @description :  OSS帮助类
 * @date 2019-09-02
 * @return
 */
@Component
public class OSSUtil {

    private Logger logger=Logger.getLogger(this.getClass());

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    @Value("${endpoint}")
    private String endpoint;
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${accessKeySecret}")
    private String accessKeySecret;
    @Value("${bucketName}")
    private String bucketName;


    /**
     * @return OSS oss客户端
     * @throws
     * @Title: getOSS
     * @Description: 获取oss客户端
     */

    public OSS getOSS() {
        //使用你的对应的endpoint地址
        String endpoint = this.endpoint;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = this.accessKeyId;
        String accessKeySecret = this.accessKeySecret;
//        OSS ossClient = new OSS(endpoint, accessKeyId, accessKeySecret);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        return ossClient;
    }

    /**
     * @param url        URL
     * @param objectName 上传文件目录和（包括文件名）例如“test/index.html”
     * @return void        返回类型
     * @throws
     * @Title: uploadByNetworkStream
     * @Description: 通过网络流上传文件
     */

    public void uploadByNetworkStream(URL url, String objectName) {
        OSS ossClient = getOSS();
        try {
            InputStream inputStream = url.openStream();
            ossClient.putObject(this.bucketName, objectName, inputStream);
            ossClient.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * @param inputStream 输入流
     * @param objectName  上传文件目录和（包括文件名） 例如“test/a.jpg”
     * @return void        返回类型
     * @throws
     * @Title: uploadByInputStream
     * @Description: 通过输入流上传文件
     */

    public String uploadByInputStream(InputStream inputStream, String objectName) {
        OSS ossClient = getOSS();
        try {
            PutObjectResult result= ossClient.putObject(this.bucketName, objectName, inputStream);
            return getUrl(ossClient,objectName);
        } catch (Exception e) {
            logger.info(e.getMessage(),e);
            e.printStackTrace();
            throw new MyException(e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

    /**
     * @param file       上传的文件
     * @param objectName 上传文件目录和（包括文件名） 例如“test/a.jpg”
     * @return void        返回类型
     * @throws
     * @Title: uploadByFile
     * @Description: 通过file上传文件
     */

    public void uploadByFile(File file,  String objectName) {
        OSS ossClient = getOSS();
        try {
            ossClient.putObject(this.bucketName, objectName, file);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    /**
     * @param key        文件路径/名称，例如“test/a.txt”
     * @return void            返回类型
     * @throws
     * @Title: deleteFile
     * @Description: 根据key删除oss服务器上的文件
     */

    public void deleteFile(String key) {
        OSS ossClient = getOSS();
        ossClient.deleteObject(this.bucketName, key);
    }

    /**
     * @param key        文件路径和名称
     * @return InputStream    文件输入流
     * @throws
     * @Title: getInputStreamByOSS
     * @Description:根据key获取服务器上的文件的输入流
     */

    public InputStream getInputStreamByOSS( String key) {
        OSS ossClient = getOSS();
        InputStream content = null;
        try {
            OSSObject ossObj = ossClient.getObject(bucketName, key);
            content = ossObj.getObjectContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /*
     *
     * @Title: queryAllObject
     * @Description: 查询某个bucket里面的所有文件
     * @param bucketName        bucket名称
     * @return List<String>  文件路径和大小集合
     * @throws
     */
    public List<String> queryAllObject(String bucketName) {
        OSS ossClient = getOSS();
        List<String> results = new ArrayList<String>();
        try {
            // ossClient.listObjects返回ObjectListing实例，包含此次listObject请求的返回结果。
            if (EmptyUtil.isEmpty(bucketName)) {
                bucketName = this.bucketName;
            }
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            // objectListing.getObjectSummaries获取所有文件的描述信息。
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                results.add(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return results;
    }


    public String getUrl(OSS oss,String fileName) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = oss.generatePresignedUrl(bucketName, fileName, expiration);
        if (EmptyUtil.isNotEmpty(url)) {
            return url.toString();
        }else{
            logger.info("获取图片连接失败");
            throw new MyException("图片上传失败!");
        }
    }

    public void pushStr() {
        OSS ossClient = getOSS();
        // 上传字符串。
        String content = "Hello OSS";
        ossClient.putObject("exhibition-test", "testStrs", new ByteArrayInputStream(content.getBytes()));

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}

